<#
Copyright 2012 Chris Duck

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
#>
dir (Join-Path $PSScriptRoot "*.ps1") | %{
	. $_.FullName
}

function GetLocalRepository {
	return (Split-Path -Path $PSScriptRoot -Parent)
}

function GetToolsRepository {
	$ProgramData = [Environment]::GetFolderPath([Environment+SpecialFolder]::CommonApplicationData)
	return (Join-Path $ProgramData "PS-NuGet\Tools")
}

function GetNuGetConfigXML {
	param(
		[switch]$Create
	)
	$ProgramData = [Environment]::GetFolderPath([Environment+SpecialFolder]::CommonApplicationData)
	$NuGetConfigFolder = Join-Path $ProgramData "PS-Nuget"
	$NuGetConfigFile = Join-Path $NuGetConfigFolder "PS-Nuget.config"
	
	$NuGetConfigXML = $null
	if( !(Test-Path $NuGetConfigFile) ) {
		if($Create) {
			#Create a new xml document
			Write-Debug "GetNuGetConfigXML: Config file not found at $NuGetConfigFile, creating new file"
			$TemplateXML = @"
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources default="">
  </packageSources>
	<subscriptions>
	</subscriptions>
</configuration>
"@
			$NuGetConfigXML = New-Object Xml.XmlDocument
			$NuGetConfigXML.LoadXml($TemplateXML)
		}
	} else {
		#There was already a config file hanging around, try to load it
		try {
			Write-Debug "GetNuGetConfigXML: Loading $NuGetConfigFile"
			$NuGetConfigXML = New-Object Xml.XmlDocument
			$NuGetConfigXML.Load($NuGetConfigFile)
		} catch {
			throw New-Object Exception("Unable to load PS-NuGet configuration at ${NuGetConfigFile}: $_", $_.Exception)
		}
	}
	return $NuGetConfigXML
}

function SaveNuGetConfigXML {
	param(
		[Xml.XmlDocument]$NuGetConfigXML
	)
	$ProgramData = [Environment]::GetFolderPath([Environment+SpecialFolder]::CommonApplicationData)
	$NuGetConfigFolder = Join-Path $ProgramData "PS-Nuget"
	$NuGetConfigFile = Join-Path $NuGetConfigFolder "PS-Nuget.config"
	
	#Check to make sure the parent folder exists
	if( !(Test-Path $NuGetConfigFolder) ) {
		if(!(mkdir $NuGetConfigFolder -Force)) {
			throw "Unable to create config folder at $NuGetConfigFolder"
		}
	}
	
	try {
		$NuGetConfigXML.Save($NuGetConfigFile)
	} catch {
		throw new-object Exception("Error saving ${NuGetConfigFile}: $_", $_.Exception)
	}
}